package cn.iocoder.yudao.module.hs.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashSet;

@Component
@Slf4j
public class NettyInitializer implements InitializingBean {

    @Value("${netty.port:9000}")
    public int port;

    @Override
    public void afterPropertiesSet() throws Exception {
        start();
    }

    public void start() {
        //开启新的线程,启动netty
        new Thread(() -> {
            NioEventLoopGroup bossgroup = new NioEventLoopGroup();
            NioEventLoopGroup workgroup = new NioEventLoopGroup();
            ServerBootstrap bootstrap = new ServerBootstrap();
            try {
                bootstrap.group(bossgroup, workgroup)
                        .channel(NioServerSocketChannel.class)
                        .option(ChannelOption.SO_BACKLOG, 1024)
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        .childHandler(new ChannelInitHandler());
                ChannelFuture channelFuture = bootstrap.bind(port).sync();
                channelFuture.channel().closeFuture().sync();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                bossgroup.shutdownGracefully();
                workgroup.shutdownGracefully();
            }
        }).start();
        log.info("[init][初始化 netty 端口 {} 成功]", port);
    }
}
